// src/components/Upload/utils/validator.ts
import type { ValidationResult } from '../upload/types';

/**
 * 验证文件类型
 */
export function validateFileType(file: File, allowedTypes: string[] = ['image/jpeg', 'image/png']): ValidationResult {
  const fileType = file.type || `.${file.name.split('.').pop()?.toLowerCase()}`;
  
  const isValid = allowedTypes.some(type => 
    type.startsWith('.') 
      ? fileType === type
      : fileType === type
  );
  
  if (!isValid) {
    return {
      valid: false,
      message: `仅支持 ${allowedTypes.join(', ')} 格式`
    };
  }
  
  return { valid: true };
}

/**
 * 验证文件大小
 */
export function validateFileSize(file: File, maxSizeMB: number = 2): ValidationResult {
  const maxBytes = maxSizeMB * 1024 * 1024;
  
  if (file.size > maxBytes) {
    return {
      valid: false,
      message: `文件大小不能超过 ${maxSizeMB}MB`
    };
  }
  
  return { valid: true };
}

/**
 * 验证图片尺寸
 */
export async function validateImageDimensions(
  file: File, 
  dimensions: { width: number; height: number }
): Promise<ValidationResult> {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      const valid = img.width === dimensions.width && img.height === dimensions.height;
      URL.revokeObjectURL(img.src);
      resolve({
        valid,
        message: valid ? undefined : `图片尺寸必须为 ${dimensions.width}x${dimensions.height}`
      });
    };
    img.onerror = () => resolve({ valid: false, message: '图片加载失败' });
    img.src = URL.createObjectURL(file);
  });
}

/**
 * 综合验证器
 */
export async function validateFile(
  file: File,
  options: {
    allowedTypes?: string[];
    maxSizeMB?: number;
    dimensions?: { width: number; height: number };
  } = {}
): Promise<ValidationResult> {
  // 类型验证
  if (options.allowedTypes) {
    const typeValidation = validateFileType(file, options.allowedTypes);
    if (!typeValidation.valid) return typeValidation;
  }
  
  // 大小验证
  if (options.maxSizeMB) {
    const sizeValidation = validateFileSize(file, options.maxSizeMB);
    if (!sizeValidation.valid) return sizeValidation;
  }
  
  // 尺寸验证
  if (options.dimensions) {
    return await validateImageDimensions(file, options.dimensions);
  }
  
  return { valid: true };
}